package com.kotlin.android.api.config

import com.kotlin.android.core.CoreApp
import com.kotlin.android.ktx.ext.safeClose
import java.io.*
import java.util.*

/**
 * app构建配置
 *
 * Created on 2020/5/6.
 *
 * @author o.s
 */
class AppConfig private constructor() {

    companion object {
        val instance by lazy { AppConfig() }
    }

    val api: String
    val branch: String
    val channel: String
    val umeng: String
    val isNbs: Boolean

    init {
        var api: String = ""
        var branch: String = ""
        var channel: String = ""
        var umeng: String = ""
        var isNbs: Boolean = false

        var fis: InputStream? = null
//        var isr: InputStreamReader? = null
//        var br: BufferedReader? = null
        try {
            fis = CoreApp.instance.assets.open(ApiConfig.CONFIG_FILE_NAME)

            val props = Properties()
            props.load(fis)

            api = props.getProperty("api")
            branch = props.getProperty("branch")
            channel = props.getProperty("channel")
            umeng = props.getProperty("umeng")
            isNbs = props.getProperty("isNbs")?.toBoolean() ?: false

//            isr = InputStreamReader(fis)
//            br = BufferedReader(isr)
//            var line: String? = null
//
//            while (
//                {
//                    line = br.readLine()
//                    line
//                }() != null) {
//                val list = line?.split('=')
//                list?.apply {
//                    if (size == 2) {
//                        val key = list[0].trim()
//                        val value = list[1].trim().toLowerCase(Locale.ROOT)
//                        when (key) {
//                            "api" -> api = value
//                            "branch" -> branch = value
//                            "channel" -> channel = value
//                            "umeng" -> umeng = value
//                            "isNbs" -> isNbs = value.toBoolean()
//                        }
//                    }
//                }
//            }
        } catch (e: Throwable) {
            e.printStackTrace()
        } finally {
            this.api = api
            this.branch = branch
            this.channel = channel
            this.umeng = umeng
            this.isNbs = isNbs

//            br.safeClose()
//            isr.safeClose()
            fis.safeClose()
        }
    }
}